<?php

namespace app\models;

use Yii;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "sys_user".
 *
 * @property int $userid
 * @property string $user_account
 * @property string|null $user_passwd
 * @property string|null $password_hash
 * @property string $user_name
 * @property string $user_status
 * @property string|null $user_mobile
 * @property int $ischeck_mobile
 * @property string|null $user_email
 * @property int|null $ischeck_email
 * @property string|null $user_type
 * @property string|null $access_token
 * @property int|null $token_utc
 * @property int $is_delete
 */
class SysUser extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'sys_user';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['user_account', 'user_name'], 'required'],
            [['ischeck_mobile', 'ischeck_email', 'token_utc', 'is_delete'], 'integer'],
            [['user_account', 'user_passwd', 'user_name', 'user_status', 'user_mobile', 'user_type'], 'string', 'max' => 50],
            [['password_hash', 'access_token'], 'string', 'max' => 32],
            [['user_email'], 'string', 'max' => 100],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'userid' => 'Userid',
            'user_account' => 'User Account',
            'user_passwd' => 'User Passwd',
            'password_hash' => 'Password Hash',
            'user_name' => 'User Name',
            'user_status' => 'User Status',
            'user_mobile' => 'User Mobile',
            'ischeck_mobile' => 'Ischeck Mobile',
            'user_email' => 'User Email',
            'ischeck_email' => 'Ischeck Email',
            'user_type' => 'User Type',
            'access_token' => 'Access Token',
            'token_utc' => 'Token Utc',
            'is_delete' => 'Is Delete',
        ];
    }

    /**
     * Finds an identity by the given ID.
     * @param string|int $id the ID to be looked for
     * @return IdentityInterface|null the identity object that matches the given ID.
     * Null should be returned if such an identity cannot be found
     * or the identity is not in an active state (disabled, deleted, etc.)
     */
    public static function findIdentity($id)
    {
        // TODO: Implement findIdentity() method.
        return self::findOne(['userid'=>$id,'is_delete'=>0]);
    }

    /**
     * Finds an identity by the given token.
     * @param mixed $token the token to be looked for
     * @param mixed $type the type of the token. The value of this parameter depends on the implementation.
     * For example, [[\yii\filters\auth\HttpBearerAuth]] will set this parameter to be `yii\filters\auth\HttpBearerAuth`.
     * @return IdentityInterface|null the identity object that matches the given token.
     * Null should be returned if such an identity cannot be found
     * or the identity is not in an active state (disabled, deleted, etc.)
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        // TODO: Implement findIdentityByAccessToken() method.
        return self::findOne(['access_token'=>$token,'is_delete'=>0]);
    }

    /**
     * Returns an ID that can uniquely identify a user identity.
     * @return string|int an ID that uniquely identifies a user identity.
     */
    public function getId()
    {
        // TODO: Implement getId() method.
        return $this->userid;
    }

    /**
     * Returns a key that can be used to check the validity of a given identity ID.
     *
     * The key should be unique for each individual user, and should be persistent
     * so that it can be used to check the validity of the user identity.
     *
     * The space of such keys should be big enough to defeat potential identity attacks.
     *
     * The returned key is used to validate session and auto-login (if [[User::enableAutoLogin]] is enabled).
     *
     * Make sure to invalidate earlier issued authKeys when you implement force user logout, password change and
     * other scenarios, that require forceful access revocation for old sessions.
     *
     * @return string|null a key that is used to check the validity of a given identity ID.
     * @see validateAuthKey()
     */
    public function getAuthKey():?string
    {
        // TODO: Implement getAuthKey() method.
        return $this->access_token;
    }

    /**
     * Validates the given auth key.
     *
     * @param string $authKey the given auth key
     * @return bool whether the given auth key is valid.
     * @see getAuthKey()
     */
    public function validateAuthKey($authKey):bool
    {
        // TODO: Implement validateAuthKey() method.
        return $this->access_token === $authKey;
    }

    /**
     * Finds user by username
     *
     * @param string $user_account
     * @return ?SysUser
     */
    public function findByUserAccount(string $user_account): ?SysUser
    {
        return  self::findOne(['user_account'=>$user_account,'is_delete'=>0]);
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($user, string $password): bool
    {
        // return true;
        // return $this->password_hash === $this->encryptPassword($password);
        return $user->user_passwd == $password;
    }

    /**
     * 密码加密
     * @param string $password
     * @return string
     */
    private function encryptPassword(string $password):string
    {
        return md5($password."test123456");
    }
}
